<template>
  <div
    ref="monacoRef"
    :style="{ width: props.width, height: props.height, border: '1px solid #ccc' }"
  ></div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as monaco from 'monaco-editor'

const monacoRef = ref()
let monacoEditor:monaco.editor.IStandaloneCodeEditor | null = null
const props = defineProps({
  width: {
    type: String,
    default: '300px'
  },
  height: {
    type: String,
    default: '200px'
  },
  modelValue: {
    type: String,
    default: '中华人民共和国'
  },
  isEdit: {
    type: Boolean,
    default: true
  },
  language: {
    type: String,
    default: 'text'
  }
})
const monacoParams = {
  theme: 'vs-black', // 主题
  value: props.modelValue, // 默认显示的值
  language: props.language,
  folding: true, // 是否折叠
  foldingHighlight: true, // 折叠等高线
  foldingStrategy: 'indentation', // 折叠方式  auto | indentation
  showFoldingControls: 'always', // 是否一直显示折叠 always | mouseover
  disableLayerHinting: true, // 等宽优化
  emptySelectionClipboard: false, // 空选择剪切板
  selectionClipboard: false, // 选择剪切板
  automaticLayout: true, // 自动布局
  codeLens: false, // 代码镜头
  scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
  colorDecorators: false, // 颜色装饰器
  accessibilitySupport: 'off', // 辅助功能支持  "auto" | "off" | "on"
  lineNumbers: 'on', // 行号 取值： "on" | "off" | "relative" | "interval" | function
  lineNumbersMinChars: 5, // 行号最小字符   number
  enableSplitViewResizing: false,
  readOnly: !props.isEdit, // 是否只读  取值 true | false
  tabSize: 2,
  minimap: {
    enabled: false
  },
  wordWrap: 'on' // 启用自动换行
}
const initMonaco = () => {
  // @ts-ignore
  monacoEditor = monaco.editor.create(monacoRef.value, monacoParams)
}
watch(() => props.isEdit, (val: Boolean) => {
  monacoEditor?.updateOptions({
    readOnly: !val
  })
})
watch(() => props.modelValue, (val: string) => {
  if (!props.isEdit) {
    monacoEditor?.setValue(val)
  }
})

const $emit = defineEmits(['update:modelValue'])
onMounted(() => {
  initMonaco()
  monacoEditor?.onDidChangeModelContent(() => {
    if (props.isEdit) {
      const mid = monacoEditor?.getValue()
      $emit('update:modelValue', mid)
    }
  })
})
</script>
